<template>
    <div class="container">
        <el-form :model="searchForm" ref="searchFormRef" label-width="80px" class="mb-4"
            style="display: flex; align-items: center; flex-wrap: wrap;">
            <el-row :gutter="20" style="flex: 1; display: flex;">
                <el-col :span="6">
                    <el-form-item label="报损单号:">
                        <el-input v-model="searchForm.Lossreportnumber" placeholder="输入入库单号" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="单据类型:">
                        <el-select v-model.number="searchForm.Thetypeoflossreport" placeholder="请选择">
                            <el-option label="损坏报损" value="损坏报损"></el-option>
                            <el-option label="丢失报损" value="丢失报损"></el-option>
                            <el-option label="其他报损" value="其他报损"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="单据状态:">
                        <el-select v-model.number="searchForm.Reviewstatus" placeholder="请选择">
                            <el-option label="待审核" value="101"></el-option>
                            <el-option label="审核成功" value="102"></el-option>
                            <el-option label="审核失败" value="103"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-button type="primary" @click="mockData" style="margin-left: 10px;">
                查询
            </el-button>
            <el-button @click="handleReset" style="margin-left: 10px;">
                重置
            </el-button>
        </el-form>

        <div class="export-button-container">
            <el-button @click="addLeage">新增</el-button>
            <el-button @click="batchExport">编辑</el-button>
            <el-button @click="Deleteinbulk">删除</el-button>
            <el-button @click="mockData">刷新</el-button>
            <el-button @click="batchExport">导出</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" ref="tableRef" style="width: 100%">
            <el-table-column type="selection">
            </el-table-column>
            <el-table-column prop="lossreportnumber" label="报损单号" />
            <el-table-column prop="productname" label="产品名称" />
            <el-table-column prop="productcode" label="产品编号" />
            <el-table-column prop="batch" label="批次" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="reportedlossquantity" label="数量" />
            <el-table-column prop="warehouse" label="仓库" />
            <el-table-column prop="warehouse" label="原库位" />
            <el-table-column prop="thecurrentlocation" label="报损库位" />
            <el-table-column prop="thetypeoflossreport" label="报损类型" />
            <el-table-column prop="reviewstatus" label="状态">
                <template #default="scope">
                    {{ scope.row.reviewstatus == 101 ? "待处理" : "" }}
                    {{ scope.row.reviewstatus == 102 ? "已通过" : "" }}
                    {{ scope.row.reviewstatus == 103 ? "已拒绝" : "" }}
                </template>
            </el-table-column>
            <el-table-column prop="reviewers" label="审核人" />
            <el-table-column prop="reviewtime" label="审核时间">
                <template #default="scope">
                    {{ scope.row.reviewtime ? scope.row.reviewtime.substring(0, 10) : "" }}
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="showDetail(scope.row.lossreportnumber)">
                        查看
                    </el-button>
                    <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
                        删除
                    </el-button>
                    <el-button link type="primary" size="small" @click="Update(scope.row.lossreportnumber)">
                        修改
                    </el-button>

                </template>
            </el-table-column>
        </el-table>
    </div>
    <div style=" display: flex; align-items: center; gap: 8px;">
        <el-button @click="selectAll">全选</el-button>
        <el-button @click="reverseSelect">反选</el-button>
        <el-button @click="batchHandle">批量操作</el-button>
        <div style="flex: 1;"></div>
        <el-pagination v-model:current-page="searchForm.PageIdex" v-model:page-size="searchForm.PageSize"
            :page-sizes="[1, 10, 20, 30]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="searchForm.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 报损单详情 -->
    <el-dialog title="报损单详情" v-model="detailDialogVisible" width="60%">
        <!-- 上半部分信息 -->
        <div class="detail-info">
            <!-- 第一行：入库单号、入库单类型、入库状态 -->
            <div class="info-row">
                <span class="label">报损单号：</span>
                <span>{{ detailInfo.lossreportnumber }}</span>
            </div>
            <div class="info-row">
                <span class="label">报损类型:</span>
                <span>{{ detailInfo.thetypeoflossreport }}</span>
            </div>
            <div class="info-row">
                <span class="label">单据状态：</span>
                <span>{{ detailInfo.reviewstatus }}</span>
            </div>

            <!-- 第三行：电话、制单人、制单日期 -->
            <div class="info-row">
                <span class="label">关联单号：</span>
                <span>{{ detailInfo.associatetheordernumber }}</span>
            </div>
            <div class="info-row">
                <span class="label">制单人：</span>
                <span>{{ detailInfo.makeasingle }}</span>
            </div>
            <div class="info-row">
                <span class="label">制单日期：</span>
                <span>{{ detailInfo.thetimewhentheorderwasmade ? detailInfo.thetimewhentheorderwasmade.substring(0, 10)
                    : "" }}</span>
            </div>

            <div class="info-row">
                <span class="label">备注：</span>
                <span>{{ detailInfo.remark }}</span>
            </div>
            <div class="info-row">
                <span class="label">审核原因：</span>
                <span>{{ detailInfo.reasonforreview || '无' }}</span>
            </div>
        </div>

        <!-- 下半部分表格 -->
        <el-table :data="tableDatas" style="margin-top: 20px">
            <el-table-column prop="productcode" label="产品编码" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.productcode)">
                        <span v-for="(id, index) in scope.row.productcode" :key="index">{{ id }}{{ index <
                            scope.row.productcode.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.productcode }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="productname" label="产品名称" width="200">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.productname)">
                        <span v-for="(name, index) in scope.row.productname" :key="index">{{ name }}{{ index <
                            scope.row.productname.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.productname }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格" width="100">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.specification)">
                        <span v-for="(spec, index) in scope.row.specification" :key="index">{{ spec }}{{ index <
                            scope.row.specification.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.specification }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="batch" label="批次" width="150">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.batch)">
                        <span v-for="(batch, index) in scope.row.batch" :key="index">{{ batch }}{{ index <
                            scope.row.batch.length - 1 ? ', ' : '' }}</span>
                        </span>
                        <span v-else>{{ scope.row.batch }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="reportedlossquantity" label="报损数量" width="120">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.reportedlossquantity)">
                        <span v-for="(reportedlossquantity, index) in scope.row.reportedlossquantity" :key="index">{{
                            reportedlossquantity }}{{ index < scope.row.reportedlossquantity.length - 1 ? ', ' : ''
                            }}</span>
                        </span>
                        <span v-else>{{ scope.row.reportedlossquantity }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="thecurrentlocation" label="报损数量" width="120">
                <template #default="scope">
                    <span v-if="Array.isArray(scope.row.thecurrentlocation)">
                        <span v-for="(thecurrentlocation, index) in scope.row.thecurrentlocation" :key="index">{{
                            thecurrentlocation }}{{ index < scope.row.thecurrentlocation.length - 1 ? ', ' : ''
                            }}</span>
                        </span>
                        <span v-else>{{ scope.row.thecurrentlocation }}</span>
                </template>
            </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 20px">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
    </el-dialog>

</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElTable } from 'element-plus';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { KongaUrl } from '@/axios/axiosHelp'

const router = useRouter();
const route = useRoute();
const id = route.query.id as string; // 确保类型正确
// 接口地址配置
const API_CONFIG = {
    STORE_QUERY:  'wangjunlong/api/Reportlosses/ReportlossesQuser',
    STORE_DETAIL: 'wangjunlong/api/Reportlosses/ReportlossesBate',
    STORE_DELETE: 'wangjunlong1/api/Reportlosses/ReportlossesDelete',
    STORE_EXPORT: 'wangjunlong/api/Reportlosses/ExportOrderList'
};

interface TableRow {
    id: number;
    lossreportnumber: string | null;
    thetypeoflossreport: string | null;
    associatetheordernumber: string | null;
    makeasingle: string | null;
    thetimewhentheorderwasmade: Date | null;
    remark: string | null;
    productname: string | null;
    productcode: string | null;
    specification: string | null;
    batch: string | null;
    unitprice: string | null;
    reportedlossquantity: string | null;
    warehouse: string | null;
    thecurrentlocation: string | null;
    reviewstatus: number | null;
    reviewers: string | null;
    reasonforreview: string | null;
    reviewtime: Date | null;
    isDelete: number | null;
}

const searchForm = reactive({
    Lossreportnumber: '',
    Thetypeoflossreport: '',
    Reviewstatus: '',
    PageIdex: 1,
    PageSize: 15,
    totalPage: 0,
    totalCount: 0,
});

const tableData = ref<TableRow[]>([]);
const tableRef = ref<InstanceType<typeof ElTable>>();

// 弹窗相关变量
const detailDialogVisible = ref(false);
const approvalDialogVisible = ref(false);

const handleAxiosError = (error: any) => {
    if (error.response) {
        console.error('请求失败，状态码:', error.response.status);
        console.error('响应数据:', error.response.data);
        const message = `请求失败，状态码: ${error.response.status}`;
        const result = ElMessage.error(message);
        console.log('ElMessage 调用结果:', result); // 添加这行调试信息
    } else if (error.request) {
        console.error('请求已发送，但没有收到响应');
        const message = '请求已发送，但没有收到响应';
        const result = ElMessage.error(message);
        console.log('ElMessage 调用结果:', result); // 添加这行调试信息
    } else {
        console.error('请求出错:', error.message);
        const message = '网络请求失败，请检查连接';
        const result = ElMessage.error(message);
        console.log('ElMessage 调用结果:', result); // 添加这行调试信息
    }
};

const processDetailData = (data: any) => {
    const parseData = (str: string) => {
        return (str.match(/\{([^}]+)\}/g) || []).map(item => item.slice(1, -1));
    };
    const productCodes = parseData(data.productcode);
    const productNames = parseData(data.productname);
    const specifications = parseData(data.specification);
    const batches = parseData(data.batch);
    const reportedLossQuantities = parseData(data.reportedlossquantity);
    const currentLocations = parseData(data.thecurrentlocation);

    console.log('Current locations data:', currentLocations);

    const processedData = productCodes.map((code, index) => ({
        productcode: code,
        productname: productNames[index] || '',
        specification: specifications[index] || '',
        batch: batches[index] || '',
        reportedlossquantity: reportedLossQuantities[index] || '',
        thecurrentlocation: currentLocations[index] || ''
    }));

    return processedData;
};

onMounted(() => {
    mockData();
});

const mockData = async () => {
    try {
        const res = await KongaUrl<{
            code: number;
            msg: string;
            data: {
                list: TableRow[];
                totalPage: number;
                totalCount: number;
            };
        }>(API_CONFIG.STORE_QUERY, {
            params: {
                Lossreportnumber: searchForm.Lossreportnumber,
                Thetypeoflossreport: searchForm.Thetypeoflossreport,
                Reviewstatus: searchForm.Reviewstatus,
                PageIdex: searchForm.PageIdex,
                PageSize: searchForm.PageSize,
            }
        });

        if (res.data.code === 210) {
            tableData.value = res.data.data.list;
            searchForm.totalPage = res.data.data.totalPage;
            searchForm.totalCount = res.data.data.totalCount;
            console.log('数据加载完成');
        } else {
            console.error('查询失败:', res.data.msg);
            ElMessage.error(res.data.msg);
        }
    } catch (error) {
        handleAxiosError(error);
    }
};

const handleSizeChange = (size: number) => {
    searchForm.PageSize = size;
    mockData();
};

const handleCurrentChange = (page: number) => {
    searchForm.PageIdex = page;
    mockData();
};

const handleReset = () => {
    searchForm.Lossreportnumber = '';
    searchForm.Thetypeoflossreport = '';
    searchForm.Reviewstatus = '';
    searchForm.PageIdex = 1;
    mockData();
};

// 全选
const selectAll = () => {
    if (tableRef.value) {
        tableData.value.forEach(row => {
            tableRef.value?.toggleRowSelection(row, true);
        });
        console.log('全选操作执行');
    } else {
        console.log('表格引用未初始化');
    }
};

// 反选
const reverseSelect = () => {
    if (tableRef.value) {
        tableData.value.forEach(row => {
            tableRef.value?.toggleRowSelection(row);
        });
        console.log('反选操作执行');
    } else {
        console.log('表格引用未初始化');
    }
};

// 批量操作
const batchHandle = () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择数据');
        return;
    }
    console.log('批量操作数据:', selected);
    // 这里添加实际业务逻辑（如调用接口）
};

// 处理复选框选择状态改变
const handleCheckboxChange = (val: boolean, row: TableRow) => {
    tableRef.value?.toggleRowSelection(row, val);
};

// 批量导出功能
const batchExport = async () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择要导出的数据');
        return;
    }
    const productIds = selected.map(item => item.id);

    try {
        const res = await KongaUrl(API_CONFIG.STORE_EXPORT, {
            params: {
                id: productIds
            },
            paramsSerializer: (params) => {
                const parts = [];
                for (const key in params) {
                    if (Array.isArray(params[key])) {
                        params[key].forEach((value) => {
                            parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                        });
                    } else {
                        parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`);
                    }
                }
                return parts.join('&');
            },
            responseType: 'blob'
        });
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        saveAs(blob, '批量库存数据.xlsx');
    } catch (error) {
        ElMessage.error('批量导出失败，请联系管理员');
        console.error('批量导出错误:', error);
    }
};

const handleClick = (id: number) => {
    ElMessageBox.confirm(
        '确定删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const url = `${API_CONFIG.STORE_DELETE}?Id=${id}`;
            KongaUrl.post(url, {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then((res) => {
                if (res.data.code === 204) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                    mockData();
                } else {
                    ElMessage.error('删除失败')
                    mockData();
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消',
            })
        })
};

const addLeage = () => {
    // 这里原代码参数问题，暂时保留逻辑，若有需要可修改
    router.push('/ReportlossesAdd')
};

const tableDatas = ref<TableRow[]>([]);
const detailInfo = ref<TableRow>({} as TableRow);

// 移除原processDetailData函数，直接使用单个产品数据
const showDetail = (lossreportnumber: string) => {
    KongaUrl(`${API_CONFIG.STORE_DETAIL}?Lossreportnumber=${lossreportnumber}`).then((res) => {
        console.log(res)
        if (res.data.data && res.data.data.length > 0) {
            tableDatas.value = res.data.data;
            detailInfo.value = res.data.data[0]; // 详情信息取第一个产品的即可
            detailDialogVisible.value = true;
        }
    }).catch(handleAxiosError);
};

// 编辑
const Update = (lossreportnumber: string) => {
    console.log(lossreportnumber)
    router.push(`/ReportlossesUpdate?lossreportnumber=${lossreportnumber}`)
};

const ShenPi = (id: number) => {
    KongaUrl(`${API_CONFIG.STORE_DETAIL}?Id=${id}`).then((res) => {
        if (res.data.data && res.data.data.length > 0) {
            const data = res.data.data[0];
            tableDatas.value = processDetailData(data);
            detailInfo.value = data;
            approvalDialogVisible.value = true;
            nextTick(() => {
                console.log('数据更新，尝试重新渲染');
            });
        }
    }).catch(handleAxiosError);
};
// 批量删除
const Deleteinbulk = async () => {
    const selected = tableRef.value?.getSelectionRows() || [];
    if (selected.length === 0) {
        ElMessage.warning('请选择要删除的数据');
        return;
    }

    const ids = selected.map(item => item.id);
    const confirm = await ElMessageBox.confirm(
        '确定要批量删除这些数据吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    );

    if (confirm === 'confirm') {
        try {
            const url = `${API_CONFIG.STORE_DELETE}`;
            const params = new URLSearchParams();
            ids.forEach(id => params.append('Id', id.toString()));
            const res = await KongaUrl.post(`${url}?${params.toString()}`, null, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (res.data.code === 204) {
                ElMessage.success('批量删除成功');
                mockData();
            } else {
                ElMessage.error('批量删除失败');
            }
        } catch (error) {
            handleAxiosError(error);
        }
    }
};
</script>

<style scoped>
.container {
    padding: 20px;
}

.mb-4 {
    margin-bottom: 16px;
}

.export-button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
}

.detail-info {
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
}

.info-row {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    width: 50%;
}

.label {
    width: 120px;
    font-weight: 500;
    margin-right: 10px;
    text-align: right;
}

.el-table th,
.el-table td {
    border: 1px solid #e4e7ed;
}

.el-table th {
    background-color: #f5f7fa;
}

.el-button {
    margin: 0 5px;
}
</style>